<template>
    <!-- <div id="risk-order-content" class="order-content"> -->
    <div>
        <el-row class="risk-order-top">
            <el-col :span="12" class="form-col col-box">
                <!-- 指令表单 -->
                <el-row class="form-content">
                    <!-- 融资买入 -->
                    <MarginTradingForm
                        :key="renderCountKey"
                        :orderDirection="'C'"
                        :form="instInfo"
                        :tableSelectedStockInfo="tableSelectedStockInfo"
                        @getOrderForm="getOrderForm"
                        @getStockInfo="getStockInfo"
                    />
                </el-row>
                <!-- 操作按钮栏 -->
                <el-row class="form-operate">
                    <el-col :span="7">
                        <i style="font-size: 25px" name="entrySetting" class="el-icon-setting iconClass" @click="entryGroupDialog = true"></i>
                    </el-col>
                    <el-col :span="17" style="padding-left: 10px">
                        <el-button name="重置" size="mini" @click="handleClickButtonReset">重置</el-button>
                        <el-button name="试算" type="primary" size="mini" @click="handleTrialCalculate">试算</el-button>
                        <el-button name="下单" type="primary" size="mini" @click="handlePlaceOrder">下单</el-button>
                    </el-col>
                </el-row>
            </el-col>
            <!-- 持仓 -->
            <el-col :span="12" class="col-box">
                <el-tabs type="card" v-model="positionActivePane">
                    <el-tab-pane label="可申购证券信息" name="1">
                        <RiskTable
                            class="position1"
                            :msg="purchaseStockListMsg"
                            @getList="queryPurchaseStockList"
                            @handleFilter="handleFilterPurchaseStock"
                            @handleBtn="handlePurchaseStockSelect"
                            @handleSort="handleSort(arguments)"
                        ></RiskTable>
                    </el-tab-pane>
                </el-tabs>
            </el-col>
        </el-row>
        <!-- 试算结果相关 -->
        <!-- <el-row class="risk-order-bottom">
            <h3>
                <el-row class="result-span">
                    <el-col :span="3">
                        <span>风控结果:</span>
                        <status-tag :code="trailResultMsg.riskResult"></status-tag>
                    </el-col>
                    <el-col :span="6">
                        <span>试算/下单时间: </span>
                        <span style="color: red">{{ trailResultMsg.calcTime }}</span>
                    </el-col>
                    <el-col :span="5">
                        <span>计算耗时: </span>
                        <span style="color: red">{{ trailResultMsg.takeTime }}</span>
                    </el-col>
                    <el-col :span="6">
                        <span>条目检查数:</span>
                        <span v-show="riskResultTable.length" style="color: red">{{ riskResultTable.length }}</span>
                    </el-col>
                    <el-col :span="4">
                        <el-button style="float: right" type="primary" size="mini" @click="layoutDialog = true">布局设置</el-button>
                    </el-col>
                </el-row>
            </h3>
            <TrailResult :riskResultTable="riskResultTable" :showFieldList="showFieldList" />
        </el-row> -->

        <!-- 布局设置 -->
        <!-- <RiskTableLayout
            title="页面布局"
            :visible.sync="layoutDialog"
            :field-list="tableColumns"
            :selected-field-list="selectedFieldList"
            :fixed-field-list="fixedFieldList"
            table-name="UNDER_NET_ORDER"
            @on-submit="onSubmit"
        /> -->

        <!-- 条目组设置 -->
        <EntryGroupSetting
            v-if="entryGroupDialog"
            :resourceCode="resourceCode"
            :transDialog="entryGroupDialog"
            @getEntryGroup="getEntryGroup"
            @closeEntryDialog="closeEntryDialog"
        />

        <!--处理下单后的弹窗-->
        <RiskOrderResultAfter
            v-if="orderCancelShow"
            :key="riskOrderResultAfterKey"
            :riskResultThresholdType="trailResultMsg.riskResult"
            :res="riskOrderResultTable"
            @riskResultContinue="riskResultContinue"
            @riskResultCancel="riskResultCancel"
        />
    </div>
</template>
<script lang="ts">
import { Component, Prop, Vue, Watch } from 'vue-property-decorator';
import RiskTableLayout from '@/common/components/risk-table-layout.vue';
import EntryGroupSetting from '../components/entry-group-seting.vue';
import RiskTable from '@/common/components/risk-table.vue';
import MarginTradingForm from '../components/margin-trading-form.vue';
import RiskOrderResultAfter from '../components/risk-order-result-after.vue';
import MarginTradingOderClass from '../class/margin-trading-order-class';
import StatusTag from '@/pages/risk-measure/components/status-tag.vue';
import BranchTag from '@/pages/risk-measure/components/branch-tag.vue';
import TrailResult from '../components/trail-result.vue';
import { getActiveMenuCode } from '@/utils/user-util';
import { querySubsStock } from '../api/margin-trading';
import moment from 'moment';

@Component({
    name: 'MarginSubscriptionOrder',
    components: {
        RiskTableLayout,
        RiskTable,
        RiskOrderResultAfter,
        EntryGroupSetting,
        MarginTradingForm,
        StatusTag,
        BranchTag,
        TrailResult,
    },
})
// 融资融券申购下单tab
export default class MarginSubscriptionOrder extends MarginTradingOderClass {
    @Prop() activePane: string;
    @Prop()
    detail: any;
    instInfo: any = {};

    iconDom: any = null;
    stockLoading: boolean = false;
    // tableSelectedStockInfo: any = {};

    // 可申购证券信息
    purchaseStockListMsg: any = {
        returnData: { data: [], total: 0 },
        dataKey: 'data',
        title: this.ColumnUtil.PurchaseStockColumns,
        height: '100%',
        hidePage: false,
        checked: { on: false, option: false },
    };
    entryGroupDialog: boolean = false;
    isFirst: boolean = true;
    stockInfo: any = {};

    @Watch('activePane', { immediate: true })
    async onWatchActivePane() {
        if (this.activePane === '8') {
            if (this.isFirst) {
                this.getUserSelectEntryGroupList();
                this.queryPurchaseStockList(this.pages);
                this.isFirst = false;
            }
        }
    }

    // 获取要修改的指令信息
    @Watch('detail', { immediate: true, deep: true })
    onWatchDetail() {
        if (this.detail?.instNo && this.detail?.orderDirectionName == '申购') {
            let instruction: any = {};
            this.isUpdate = true;
            this.oldOuterOrderCode = this.detail.outerOrderCode;
            this.serialNo = this.detail.serialNo;
            for (const key in this.detail) {
                instruction[key] = this.detail[key];
            }
            instruction.businClass = this.detail.businessType;
            instruction.fundAccountCode = this.detail.groupCode;
            this.handleStockStatus(this.purchaseStockListMsg.returnData.data, this.detail?.stockCode);
            // this.getUserSelectEntryGroupList();
            this.instruction = JSON.parse(JSON.stringify(instruction));
            this.instInfo = JSON.parse(JSON.stringify(instruction));
            this.renderCountKey++;
        } else {
            this.instInfo = {};
        }
    }

    mounted() {
        this.resourceCode = getActiveMenuCode().defaultActive;
        this.entryTypeArr = this.objToArr(this.Invest.entryType);
        this.ThresholdTypeArr = this.objToArr(this.Invest.ThresholdType);
        // this.queryLayout();
        // this.queryPurchaseStockList(this.pages);
    }

    /* **************************** 持仓相关start *************************** */
    // 查询可申购证券信息
    queryPurchaseStockList(pages: any) {
        this.stockLoading = true;
        querySubsStock({
            paging: pages,
            ...this.queryPositionForm,
        }).then((res: any) => {
            this.purchaseStockListMsg.returnData.data = res.list;
            this.purchaseStockListMsg.returnData.total = res.total;
            this.handlePurchaseStockStatus(this.instruction?.stockCode);
            this.stockLoading = false;
        });
    }

    // 可申购证券表格筛选
    handleFilterPurchaseStock(filterList: any) {
        this.queryPositionForm = {
            sort: '',
        };
        if (filterList.length) {
            filterList.forEach(ele => {
                if (['assureType', 'attachWarrant', 'purchasingType'].includes(ele.property)) {
                    this.queryPositionForm[ele.property] = ele.values;
                } else if (ele.property == 'marketName') {
                    this.queryPositionForm['marketNo'] = ele.values;
                } else if (ele.property == 'applyTypeName') {
                    this.queryPositionForm['applyType'] = ele.values;
                } else if (ele.property == 'stockTypeName') {
                    this.queryPositionForm['stockType'] = ele.values;
                } else {
                    this.queryPositionForm[ele.property] = ele?.datas[0] || '';
                }
            });
        }
        this.queryPurchaseStockList(this.pages);
    }

    // 可申购证券表格排序
    handleSort(args: any) {
        const sortType = args[1] == 'asc' ? 'ASC' : args[1] == 'desc' ? 'DESC' : '';
        let sort = '';
        if (sortType) {
            sort = this.handleSortField(args[0], sortType);
        } else {
            sort = '';
        }
        this.queryPositionForm.sort = sort;
        this.queryPurchaseStockList(this.pages);
    }

    // 获取排序字段
    handleSortField(name: string, order: string): string {
        let value = '';
        let field = '';
        const allFields = this.ColumnUtil.purchaseSortFields;
        for (const key in allFields) {
            if (name === key) {
                field = allFields[key];
            }
        }
        value = field + ' ' + order;
        return value;
    }

    handlePurchaseStockSelect(obj: any) {
        this.tableSelectedStockInfo = obj.row;
        this.handlePurchaseStockStatus(this.tableSelectedStockInfo?.stockCode);
    }

    // 设置可申购证券勾选状态
    handlePurchaseStockStatus(stockCode: string) {
        this.purchaseStockListMsg.returnData.data.forEach(ele => {
            if (stockCode === ele.stockCode) {
                this.$set(ele, 'disabled', true);
            } else {
                this.$set(ele, 'disabled', false);
            }
        });
    }

    // 获取子组件表单数据
    getOrderForm(data: any) {
        for (const key in data) {
            this.instruction[key] = data[key];
        }
    }

    // 获取子组件选择的证券信息
    getStockInfo(data: any) {
        this.stockInfo = data;
        this.tableSelectedStockInfo = data;
        // 设置表格中相应证券选中状态
        this.handlePurchaseStockStatus(data?.stockCode);
    }

    /* **************************** 持仓相关end *************************** */

    /* ******************************* 试算、下单start *************************** */
    // 重置表单
    handleClickButtonReset() {
        super.handleClickButtonReset();
        this.handlePurchaseStockStatus(this.tableSelectedStockInfo?.stockCode);
    }

    // 表单校验
    handleVerifyInstructionParam(instruction: any) {
        let stockInfo: any = {};
        if (JSON.stringify(this.tableSelectedStockInfo) != '{}') {
            stockInfo = this.tableSelectedStockInfo;
        } else {
            stockInfo = this.stockInfo;
        }
        const verifyParams: any = {
            fundCode: '产品编码',
            fundAccountCode: '组合编码',
            stockCode: '证券代码',
            orderPrice: '指令价格',
            orderAmount: '指令数量',
            orderBalance: '指令金额',
        };
        if (instruction.orderPriceType === '2') {
            delete verifyParams.orderPrice;
        }
        // if (moment(this.tableSelectedStockInfo.payLimitDate.toString()).isBefore(moment().format('YYYYMMDD'))) {
        //     this.yh_message_warn('输入证券已经申购截止，不允许再做网下申购！');
        //     return false;
        // }
        for (const key in verifyParams) {
            if (!instruction[key]) {
                this.yh_message_warn(verifyParams[key] + '不可为空');
                return false;
            }
        }
        if (instruction.orderAmount === '0.00') {
            this.yh_message_warn('申购数量不能为0！');
            return false;
        }
        if (Number(instruction.orderPrice) < Number(stockInfo.lowerPrice) || Number(instruction.orderPrice) > Number(stockInfo.upperPrice)) {
            this.yh_message_warn('申购价格须在价格区间[' + stockInfo.lowerPrice + '，' + stockInfo.upperPrice + ']内！');
            return false;
        }
        return true;
    }
    // 试算
    handleTrialCalculate() {
        this.handleFormSubmit('1');
    }

    // 下单
    handlePlaceOrder() {
        this.handleFormSubmit('2');
    }

    // 继续下达
    riskResultContinue() {
        super.riskResultContinue();
    }

    // 终止下达
    riskResultCancel() {
        super.riskResultCancel();
    }
    /* ******************************* 试算、下单end *************************** */

    /* ************************************ 条目组设置start ********************************** */

    getEntryGroup(value: any) {
        this.getEntryGroups(value);
    }

    closeEntryDialog() {
        this.closeEntryDialogs();
    }
    /* ************************************ 条目组设置end ********************************** */
}
</script>
<style lang="scss" scoped>
@import '@/pages/risk-measure/style/measure';
@import '@/pages/risk-time/styles/risk-order';
</style>
<style lang="scss">
.messageStyle {
    background-color: #ecf9e3;
    border-color: #ecf9e3;
    font-size: 18px;
    .el-icon-success {
        color: #67c23a;
    }
}
</style>
